/*
 * Copyright (C) 2017--2019, 微笑的丁总 All rights reserved
 * Author: DingJie
 * FileName: AliOSSController
 * Date: 2019/4/26 9:55 AM
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号             描述
 */
package com.dimple.project.common;

import com.dimple.common.utils.Face2ObjectUtils;
import com.dimple.common.utils.file.aliyun.OSSUtils;
import com.dimple.framework.aspectj.lang.annotation.Log;
import com.dimple.framework.aspectj.lang.enums.BusinessType;
import com.dimple.framework.web.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author dogjay
 * @create 2019/4/26
 * @since 1.0.0 阿里云OSS图片上传处理
 */
@Controller
@Slf4j
@RequestMapping("/alioss/image")
public class AliOSSController {

    @Autowired
    OSSUtils ossUtils;

    @PostMapping("/upload")
    @Log(title = "图片管理", businessType = BusinessType.UPLOAD)
    @RequiresPermissions("alioss:image:upload")
    @ResponseBody
    public AjaxResult upload(@RequestParam("file") MultipartFile file) {
        String fname = file.getOriginalFilename();
        Map<String, String> resultMap = new HashMap<String, String>();
        //判断图片大小位置
//        if (file.getSize() <= WebConst.MAX_FILE_SIZE) {

        String fkey = fname;
        String ftype = ossUtils.getContentType(file.getOriginalFilename());
        File tempFile = new File(Face2ObjectUtils.getUploadFilePath() + fkey);
        try {
            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(tempFile));
//                        备份OSS
            resultMap = ossUtils.uploadFileToOSS(tempFile.getAbsolutePath());
            if (resultMap.get("success").equals("true")) {
                fkey = resultMap.get("filePath");
            }

            tempFile.delete();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
//            attachService.save(fname, fkey, ftype, uid);
//        } else {
//            errorFiles.add(fname);
//        }
//        String result = ossUtils.uploadImgToAliOSS(file);
        return AjaxResult.success().put("data", resultMap.get("filePath"));
    }
}
